package com.tyl.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 独占锁（写锁）一次只能被一个线程占有
 * 共享锁（读锁）多个线程可以同时占有
 * ReadWriteLock
 * 读-读 可以共存
 * 读-写 不能共存
 * 写-写 不能共存
 * **/
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache2 myCache=new MyCache2();
        for (int i = 1; i < 10; i++) {
            final int temp=i;
            new Thread(()->{
                myCache.put(temp+" ",temp+" ");
            },String.valueOf(i)).start();
        }

        for (int i = 1; i < 10; i++) {
            final int temp=i;
            int finalI = i;
            new Thread(()->{
                myCache.get(finalI+"");
            },String.valueOf(i)).start();
        }
    }
}
//自定义的缓存使用读写锁
class MyCache2{
    private volatile Map<String, Object>map=new HashMap<>();
    ReadWriteLock readWriteLock=new ReentrantReadWriteLock();
    //写
    public void put(String key,Object value){
        readWriteLock.writeLock().lock();//写的时候按顺序写
        try {
            System.out.println(Thread.currentThread().getName()+"写入"+key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入成功");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();//解锁
        }
    }
    //读
    public void get(String key){
        readWriteLock.readLock().lock();//读的时候可以插队
        try {
            System.out.println(Thread.currentThread().getName()+"读取"+key);
            map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取成功");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();//解锁
        }
    }
}




//自定义的缓存没有使用读写锁
class MyCache{
    private volatile Map<String, Object>map=new HashMap<>();

    //写
    public void put(String key,Object value){
        System.out.println(Thread.currentThread().getName()+"写入"+key);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写入成功");
    }
    //读
    public void get(String key){
        System.out.println(Thread.currentThread().getName()+"读取"+key);
        map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取成功");
    }
}
